package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long user = UserHolder.getUser().getId();
        //查询收件箱
        String key="feed:"+user;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, 0, max, offset, 5);
        if (typedTuples==null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //解析数据blogid，时间戳，offset
        //用集合接受id
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long mintime=0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            long time = typedTuple.getScore().longValue();
            if (mintime==time){
                os++;
            }else {
                mintime=time;
                os=1;
            }
        }
        //根据id查询blog
        String string = StrUtil.join(",", ids);
        List<Blog> id = query().in("id", ids).last("order by field(id," + string + ")").list();
        for (Blog blog : id) {
            queryblog(blog);
            islike(blog);
        }
        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(id);
        scrollResult.setMinTime(mintime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }

    @Autowired
    private IFollowService followService;
    @Override
    public Result saveblog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = blogService.save(blog);
        if (!save){
            return Result.fail("笔记保存失败");
        }
        //根据笔记查粉丝
        List<Follow> follow = followService.query().eq("follow_user_id", user.getId()).list();
        //推送给所有粉丝
        for (Follow follow1 : follow) {
            //获取粉丝id
            Long id = follow1.getUserId();
            //保存到redis
            String key="feed:"+id;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //查询top5点赞用户
        Set<String> range = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY+id, 0, 4);
        if (range==null ||range.isEmpty()){
            return Result.ok();
        }
        //解析用户id
        List<Long> collect = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String string = StrUtil.join(",", collect);
        //查询用户
        List<UserDTO> dto = userService.query().in("id", collect).last("order by field(id," + string + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(dto);
    }

    public static final String BLOG_LIKED_KEY = "blog:liked:";
    @Override
    public Result hotblog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            queryblog(blog);
            islike(blog);
        });
        return Result.ok(records);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IBlogService blogService;
    @Override
    public Result likeblog(Long id) {
        //获取用户id
        Long userid= UserHolder.getUser().getId();
        //判断当前用户是否点赞
        String key="blog:liked:"+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userid.toString());
        if (score==null ){
            //未点赞，可以点赞
            // 修改点赞数量
            boolean update = blogService.update().setSql("liked = liked + 1").eq("id", id).update();
            //存入redis
            if (update) {
                stringRedisTemplate.opsForZSet().add(key,userid.toString(),System.currentTimeMillis());
            }

        }else {
            boolean b = blogService.update().setSql("liked=liked-1").eq("id", id).update();
            if (b){
                stringRedisTemplate.opsForZSet().remove(key,userid.toString());
            }
        }
        return Result.ok();
    }

    @Resource
    private IUserService userService;
    @Override
    public Result watchblog(Long id) {
        Blog blog = getById(id);
        if (blog==null){
            return Result.fail("笔记不存在");
        }
        queryblog(blog);
        islike(blog);
        return Result.ok(blog);
    }

    private void queryblog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void islike(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user==null){
            return;
        }
        //是否点赞
        //获取用户id
        Long userid = user.getId();
        //判断当前用户是否点赞
        String key="blog:liked:"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userid.toString());
        blog.setIsLike(score!=null);
    }
}
